import React, { useEffect, useState } from 'react';
import cls from './index.module.less';
import { XReportTreeNode } from '@/ts/base/schema';
import { ReportTaskTreeNodeView, TaskContentType } from '@/ts/base/model';
import {
  AllReceptionStatus,
  getColorName,
  getStatus,
  ReceptionStatus,
  ReportTaskTreeSummary,
  statusMap,
} from '@/ts/core/work/assign/reception/status';
import ReportTree from '@/executor/design/reportTreeModal/ReportTree';
import { Resizable } from 'devextreme-react';
import { Button, Input, Tag, Tooltip } from 'antd';
import { SyncOutlined } from '@ant-design/icons';
import OrgIcons from '@/components/Common/GlobalComps/orgIcons';
import SchemaForm from '@/components/SchemaForm';
import { schema } from '@/ts/base';
import { ProFormColumnsType } from '@ant-design/pro-components';
import { PeriodType } from '@/ts/base/enum';
import { ReportContentForm } from '@/executor/operate/entityForm/taskContent/ReportContentForm';

interface SummaryReceptionStatusInfo {
  status: AllReceptionStatus | 'approving' | 'approved';
  label: string;
  color: string;
}

const periodTypeNames: PeriodType[] = [
  PeriodType.Year,
  PeriodType.Quarter,
  PeriodType.Month,
  PeriodType.Week,
  PeriodType.Day,
  PeriodType.Once,
  PeriodType.Any,
  PeriodType.Inventory,
  PeriodType.PropertyInventory,
  PeriodType.RevitalizeReports,
];

export function ReportTaskTree(props: {
  tree: ReportTaskTreeNodeView[];
  currentNode: XReportTreeNode | null;
  onNodeSelect: (node: ReportTaskTreeNodeView) => void;
  summary?: ReportTaskTreeSummary;
  onSyncStatus?: () => any;
  width?: number;
  loadChildren?: (parentNodeId: string) => Promise<ReportTaskTreeNodeView[]>;
  readOnly?: boolean;
}) {
  const [leftWidth, setLeftWidth] = useState(props.width ?? 430);
  const [nodeId, setNodeId] = useState('');
  const [searchText, setSearchText] = useState('');
  const [currentTag, setCurrentTag] = useState('total');
  const [open, setOpen] = useState(false);

  useEffect(() => {
    setNodeId(props.currentNode?.id || '');
  }, [props.currentNode]);
  function selectNode(e: ReportTaskTreeNodeView) {
    setNodeId(e.id);
    props.onNodeSelect(e);
  }

  function renderNode(node: ReportTaskTreeNodeView) {
    let status = getStatus(node.reception);
    let color = getColorName(statusMap[status]?.color);
    return (
      <>
        <span style={{ color }}>{node.name}</span>
        {node.reception?.isAutoFill && (
          <Tag color="green" style={{ marginLeft: 6 }}>
            自动补全
          </Tag>
        )}
      </>
    );
  }

  const taskModal = () => {
    const columns: ProFormColumnsType<schema.XAssignTaskModel>[] = [
      {
        title: '名称',
        dataIndex: 'name',
        readonly: false,
        formItemProps: {
          rules: [{ required: true, message: '任务名称为必填项' }],
        },
      },
      {
        title: '代码',
        dataIndex: 'code',
        readonly: false,
        formItemProps: {
          rules: [{ required: true, message: '任务代码为必填项' }],
        },
      },
      {
        title: '任务周期',
        dataIndex: 'periodType',
        valueType: 'select',
        fieldProps: {
          options: periodTypeNames.map((value) => ({
            value,
            label: value,
          })),
        },
        formItemProps: {
          rules: [{ required: true, message: '任务周期为必填项' }],
        },
      },
    ];

    // columns.push({
    //   title: '任务详情',
    //   dataIndex: 'content',
    //   colProps: { span: 24 },
    //   renderFormItem: (_, __, form) => {
    //     if (!initialValue.content) {
    //       return (
    //         <Button
    //           onClick={() =>
    //             form.setFieldValue('content', {
    //               type: TaskContentType.Report,
    //               directoryId: '',
    //               treeId: '',
    //               workId: '',
    //             })
    //           }>
    //           新建
    //         </Button>
    //       );
    //     }
    //     switch (initialValue.content.type) {
    //       case TaskContentType.Report:
    //         return (
    //           <ReportContentForm
    //             task={task!}
    //             value={initialValue.content!}
    //             onChange={(f) => {
    //               form.setFieldValue('content', f);
    //             }}
    //             directory={directory}
    //           />
    //         );
    //       default:
    //         return <></>;
    //     }
    //   },
    // });
    return (
      <SchemaForm<schema.XAssignTaskModel>
        open={open}
        title={'任务分发'}
        width={640}
        columns={columns}
        initialValues={{}}
        rowProps={{
          gutter: [24, 0],
        }}
        layoutType="ModalForm"
        onOpenChange={(open: boolean) => {
          if (!open) {
            setOpen(open);
          }
        }}
        onFinish={async (values) => {
          values = Object.assign({}, {}, values);
          values.typeName = '任务模板';
          // await task!.update(values);
          // props.finished();
        }}
      />
    );
  };

  const renderTag = (info: SummaryReceptionStatusInfo, child = false) => {
    const sum = props.summary!;
    let tagValue = sum[info.status as ReceptionStatus] || 0;

    const e = () => {
      return (
        <div
          key={info.status}
          className={[cls['tag'], child ? cls['is-small'] : ''].join(' ')}
          style={{
            color: info.status === currentTag ? '#FFFFFF' : getColorName(info.color),
            backgroundColor: info.status === currentTag ? '#154ad8' : '#F0F0F0',
          }}
          onClick={() => setCurrentTag(info.status)}>
          <div>{info.label}</div> <strong>{tagValue}</strong>
          {info.status == 'total' && !props.readOnly && (
            <div>
              <Tooltip title="更新状态">
                <Button
                  type={info.status === currentTag ? 'default' : 'primary'}
                  shape="circle"
                  size="small"
                  onClick={(e) => {
                    e.stopPropagation();
                    props.onSyncStatus?.();
                  }}>
                  <SyncOutlined />
                </Button>
              </Tooltip>
            </div>
          )}
        </div>
      );
    };

    if (info.status == 'approving' && !child) {
      tagValue = sum.submitted + sum.changed;
      return (
        <div className={cls['tag-wrap']}>
          {e()}
          {renderTag(statusMap.submitted, true)}
          {renderTag(statusMap.changed, true)}
        </div>
      );
    } else if (info.status == 'approved' && !child) {
      tagValue = sum.finished + sum.rejected;
      return (
        <div className={cls['tag-wrap']}>
          {e()}
          {renderTag(statusMap.finished, true)}
          {renderTag(statusMap.rejected, true)}
        </div>
      );
    } else {
      return e();
    }
  };

  return (
    <>
      <Resizable
        handles={'right'}
        width={leftWidth}
        maxWidth={640}
        minWidth={280}
        onResize={(e) => setLeftWidth(e.width)}>
        <div className={cls['tree-wrap']}>
          {props.summary && (
            <>
              <div
                className={cls['info'] + ' ' + cls['tree-tags']}
                style={{ marginBottom: '8px' }}>
                {renderTag({
                  status: 'total',
                  label: '全部',
                  color: '',
                })}
                {renderTag(statusMap.empty)}
                {renderTag(statusMap.received)}
                {renderTag({
                  status: 'approving',
                  label: '审核中',
                  color: statusMap.submitted.color,
                })}
                {renderTag({
                  status: 'approved',
                  label: '已审核',
                  color: statusMap.finished.color,
                })}
              </div>
            </>
          )}
          <div className={cls['search-box']}>
            <Input.Search
              placeholder="搜索节点"
              allowClear
              onSearch={(e) => setSearchText(e)}
            />
            {props.readOnly && (
              <div className="chat-leftBar-search_more" style={{ marginLeft: '5px' }}>
                <OrgIcons
                  type="/operate/newWork"
                  size={22}
                  notAvatar
                  title="分发界面"
                  onClick={() => {
                    setOpen(true);
                  }}
                />
              </div>
            )}
          </div>
          <div className={cls['tree-content']}>
            <ReportTree<ReportTaskTreeNodeView>
              nodes={props.tree}
              selectedKeys={nodeId ? [nodeId] : []}
              renderNode={renderNode}
              onSelect={(_, n) => {
                selectNode(n.node);
              }}
              checkable={true}
              loadChildren={props.loadChildren}
              currentTag={currentTag}
              searchText={searchText}
            />
          </div>
        </div>
      </Resizable>
      {taskModal()}
    </>
  );
}
